type EventData = { dataName?: string; data: any };
type EventCallBack = (data: EventData) => void;
class Event {
  private queue: Record<string, EventCallBack[]> = {};
  constructor() {
    this.queue = {};
  }
  $on(name: string, callback: EventCallBack) {
    this.queue[name] = this.queue[name] || [];
    this.queue[name].push(callback);
  }

  $off(name: string, callback: EventCallBack) {
    if (callback) {
      if (this.queue[name]) {
        for (let i = 0; i < this.queue[name].length; i++) {
          if (this.queue[name][i] === callback) {
            this.queue[name].splice(i, 1);
            break;
          }
        }
      }
    } else {
      delete this.queue[name];
    }
  }

  $emit(name: string, data: EventData) {
    if (this.queue[name]) {
      this.queue[name].forEach(function (callback) {
        callback(data);
      });
    }
  }
}

export default new Event();
